package com.xueqiu.movieplaymanagersystem.controller.admin;

import com.github.pagehelper.PageInfo;
import com.xueqiu.movieplaymanagersystem.model.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.xueqiu.movieplaymanagersystem.entity.*;
import com.xueqiu.movieplaymanagersystem.service.MovieService;
import com.xueqiu.movieplaymanagersystem.utils.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author xueqiu
 */
@Controller
@RequestMapping("/admin")
public class MovieController {
    @Autowired
    private MovieService movieService;

    /**
     * 跳转控制器
     *
     * @return 跳转到电影管理页面
     */
    @GetMapping({"/movieList", "/movieList.html"})
    public String listMovie() {
        return "admin/blog/movieList";
    }

    /**
     * 分页查询电影
     *
     * @param page  当前页
     * @param limit 每页条数
     * @return 可能为empty
     */
    @GetMapping("/tableMovie")
    @ResponseBody
    public JsonResult<Movie> findAll(int page, int limit) {
        JsonResult<Movie> jsonResult = new JsonResult<>();

        PageInfo<Movie> resultPageInfo = movieService.findAll(page, limit);

        jsonResult.Success(
                "查询电影成功",
                resultPageInfo.getList(),
                (int) resultPageInfo.getTotal()
        );
        return jsonResult;
    }

    /**
     * 删除电影；根据电影id
     *
     * @param id 电影id
     * @return 删除成功与否
     */
    @GetMapping("/deleteMovie/{id}")
    @ResponseBody
    public JsonResult<String> deleteById(
            @PathVariable(name = "id")
            String id
    ) {
        JsonResult<String> jsonResult = new JsonResult<>();
        if (StringUtils.isNullOrEmptyOrOnlyWhiteSpace(id)) {
            jsonResult.Error("id参数不合法；不存在id参数");
            return jsonResult;
        }

        boolean isDelete = movieService.removeById(id);

        if (!isDelete) {
            jsonResult.Error("删除失败！");
            return jsonResult;
        }
        jsonResult.Success("删除成功！");
        return jsonResult;
    }

    /**
     * 批量删除电影
     *
     * @param movies 电影名称列表
     * @return 删除成功与否
     */
    @PostMapping("/deleteMovies")
    @ResponseBody
    public JsonResult<String> deleteByIdBatch(
            @RequestParam(name = "movies[]")
            String[] movies
    ) {
        JsonResult<String> jsonResult = new JsonResult<>();
        if (movies.length == 0) {
            jsonResult.Error("名称列表参数不合法；不存在名称列表参数");
            return jsonResult;
        }

        for (String movie : movies) {
            if (StringUtils.isNullOrEmptyOrOnlyWhiteSpace(movie)) {
                jsonResult.Error("单个名称元素不合法！");
                return jsonResult;
            }
        }

        List<String> list = Arrays.asList(movies);
        int delete = movieService.removeByIdBatch(list);

        if (delete == 0) {
            jsonResult.Error("批量删除失败！");
            return jsonResult;
        }
        if (delete == movies.length) {
            jsonResult.Success("批量删除成功！");
            return jsonResult;
        }

        jsonResult.setCode(3);
        jsonResult.setMsg("部分数据未删除！");
        return jsonResult;
    }

    /**
     * 跳转控制器
     *
     * @return 跳转到上传电影信息页面
     */
    @GetMapping({"/writeMovie.html", "/writeMovie"})
    public String writeMovie() {
        return "admin/blog/writeMovie";
    }

    /**
     * 发布电影
     * @param movie 数据源
     * @param bindingResult 绑定工具
     * @param session 域
     * @return 发布是否成功
     */
    @PostMapping("/movie/publish")
    @ResponseBody
    public JsonResult<String> publish(
            @Validated
            Movie movie,
            BindingResult bindingResult,
            HttpSession session
    ) {
        JsonResult<String> jsonResult = hasError(bindingResult);
        if (jsonResult != null) {
            return jsonResult;
        }

        jsonResult = new JsonResult<>();
        User user = (User) session.getAttribute("user");
        if (StringUtils.isNullOrEmptyOrOnlyWhiteSpace(movie.getAuthor())) {
            movie.setAuthor(user.getNickName());
        }
        //执行发布
        boolean success = movieService.publish(movie);

        if (!success) {
            jsonResult.Error("电影发布失败！");
            return jsonResult;
        }
        jsonResult.Success("电影发布成功！");
        return jsonResult;
    }

    /**
     * 判断绑定工具是否鉴别出错误
     * @param bindingResult 绑定工具
     * @return 有错则返回收集的错误信息；无错则返回null
     */
    private JsonResult<String> hasError(BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            JsonResult<String> jsonResult = new JsonResult<>();
            List<ObjectError> errors = bindingResult.getAllErrors();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("[");
            for (int i = 0; i < errors.size(); i++) {
                String defaultMessage = errors.get(i).getDefaultMessage();
                stringBuilder.append(defaultMessage);
                if (i != errors.size() - 1) {
                    stringBuilder.append(",");
                }
            }
            stringBuilder.append("]");
            String errorMsg = stringBuilder.toString();
            if (errorMsg.length() == 2) {
                //代表errorMsg其实就是"[]"，是空的；代表上述收集错误消息的过程出现了错误
                errorMsg = "[收集错误消息过程出现错误]";
            }
            jsonResult.Error(errorMsg);
            return jsonResult;
        }
        //没有错误则返回null
        return null;
    }

    /**
     * 前置跳转控制器；给编辑页面存入电影信息；用来回填数据
     * @param id 电影id
     * @param model 模型参数
     * @return 错误页面或者电影预览页面
     */
    @GetMapping("/movie/preMovie/{id}")
    public String preMovie(
            @PathVariable(name = "id")
            String id,
            Model model
    ) {
        Movie movie = movieService.findById(id);
        if (movie == null) {
            return "error/404";
        }
        model.addAttribute("movie", movie);
        return "admin/blog/preMovie";
    }

    /**
     * 前置跳转控制器；给编辑页面存入电影信息；用来回填数据
     * @param id 电影id
     * @param model 模型参数
     * @return 错误页面或者电影信息编辑页面
     */
    @GetMapping("/movie/editMovie/{id}")
    public String editMovie(
            @PathVariable(name = "id")
            String id,
            Model model
    ) {
        Movie movie = movieService.findById(id);
        if (movie == null) {
            return "error/404";
        }
        model.addAttribute("movie", movie);
        return "admin/blog/editMovie";
    }

    /**
     * 更新电影信息
     * @param movie 数据源
     * @param bindingResult 绑定工具
     * @return 更新成功与否
     */
    @PostMapping("/movie/edit/publish")
    @ResponseBody
    public JsonResult<String> edit(
            @Validated
            Movie movie,
            BindingResult bindingResult
    ) {
        JsonResult<String> jsonResult = hasError(bindingResult);
        if (jsonResult != null) {
            return jsonResult;
        }

        jsonResult = new JsonResult<>();
        boolean isEdit = movieService.edit(movie);

        if (isEdit) {
            jsonResult.Success("更新成功！");
            return jsonResult;
        }

        jsonResult.Error("更新失败！");
        return jsonResult;
    }
}
